package space.jevin.jevinboot.utils.validate;

import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验分组工具类
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2021/5/11 11:30 上午
 */
public class ValidateUtil {

    /**
     * 校验参数
     *
     * @param data 检验目标
     * @throws IllegalArgumentException IllegalArgumentException
     */
    public static ValidateResult validate(@Valid Object data) {
        return validate(data, null);
    }

    /**
     * 校验参数
     *
     * @param data       检验目标
     * @param groupClass 校验规则
     * @throws IllegalArgumentException IllegalArgumentException
     */
    public static ValidateResult validate(@Valid Object data, Class<?> groupClass) {
        Validator validator = Validation.buildDefaultValidatorFactory()
                .getValidator();
        Set<ConstraintViolation<Object>> validateSet;
        if (groupClass != null) {
            validateSet = validator.validate(data, groupClass);
        } else {
            validateSet = validator.validate(data);
        }
        if (!CollectionUtils.isEmpty(validateSet)) {
            String message = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + "；" + m2)
                    .orElse("参数输入有误！");
            return new ValidateResult(false, message);
        }
        return new ValidateResult(true);
    }
}
